package se.nikmel.AnDisper.UI;

import java.util.Arrays;
import java.util.Collection;
import java.util.Map;

import se.nikmel.AnDisper.R;
import se.nikmel.AnDisper.ServerSetupActivity;
import se.nikmel.AnDisper.DisperServer.ServerInfo;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class UI_ServerConfig_Controller implements I_UI_ViewController {
	// Misc
	private static final String TAG = "UI_ServerConfig"; // Logging tag
	private final int LAYOUT_ID = R.layout.scr_enter_ip;
	//
	private ServerSetupActivity m_actParent;

	// UI Elements
	private View m_scrIPAddress;
	private EditText m_txtIPAddress;
	private Button m_btnConnect;
	private ListView m_lvwSeenServers;

	public UI_ServerConfig_Controller(ServerSetupActivity p_actParent) {
		m_actParent = p_actParent;
		// LinearLayout lnrTop;
		// Load the screen
		LayoutInflater oInflater = m_actParent.getLayoutInflater();
		m_scrIPAddress = oInflater.inflate(LAYOUT_ID, null);
		// lnrTop = (LinearLayout) m_scrIPAddress.findViewById(R.id.vgrTop);

		// Enter IP Screen
		m_btnConnect = (Button) m_scrIPAddress.findViewById(R.id.btnOk);
		m_txtIPAddress = (EditText) m_scrIPAddress.findViewById(R.id.txtIP);
		
		// Force show keyboard when textbox gets focus
//		m_txtIPAddress.setOnFocusChangeListener(new OnFocusChangeListener() {
//			public void onFocusChange(View v, boolean hasFocus) {
//				if (hasFocus) {
//					InputMethodManager mgr = (InputMethodManager) m_actParent
//							.getSystemService(Context.INPUT_METHOD_SERVICE);
//					// only will trigger it if no physical keyboard is open
//					mgr.showSoftInput(m_txtIPAddress,
//							InputMethodManager.SHOW_IMPLICIT);
//				}
//			}
//		});
		// Catch pressing Enter in the textbox as OK
		m_txtIPAddress.setOnEditorActionListener(new OnEditorActionListener() {
			public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
				if (arg2 != null && arg2.getAction() != KeyEvent.ACTION_DOWN)
					return false; // Avoid getting this event handled twice...
				onIPEntered();
				return true;
			}
		});

		m_btnConnect.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				onIPEntered();
			}
		});

		m_lvwSeenServers = (ListView) m_scrIPAddress
				.findViewById(R.id.lvwSeenServers);		
	}

	// Called from the eventhandlers Button_Click and EditText_Action
	private void onIPEntered() {
		// hide the soft keyboard (apparently it doesn't do that
		// automatically....)
		InputMethodManager imm = (InputMethodManager) m_actParent
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(m_txtIPAddress.getWindowToken(), 0);

		m_actParent.postResult(m_txtIPAddress.getText().toString());
	}

	public View getView() {
		return m_scrIPAddress;
	}

	public void setSeenServers(Map<String, ServerInfo> p_mapSeenServers) {		
		String sDefaultIP = "192.168.1.";

		if (p_mapSeenServers.size() > 0) {
			Collection<ServerInfo> colServers = p_mapSeenServers.values();
			ServerInfo[] arrServers = new ServerInfo[colServers.size()];
			int i = 0;
			for (ServerInfo oServer : colServers)
				arrServers[i++] = oServer;

			Arrays.sort(arrServers);

			m_lvwSeenServers.setAdapter(new _MyServersAdapter(m_actParent,
					arrServers));

			m_lvwSeenServers.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					ServerInfo oServer = (ServerInfo) arg1.getTag();
					m_actParent.postResult(oServer.getIP());
				}
			});
			m_lvwSeenServers.requestFocus();
		}
		else
			m_txtIPAddress.requestFocus();
		
		m_txtIPAddress.setText(sDefaultIP);
		m_txtIPAddress.setSelection(sDefaultIP.length());
	}


	public String getIP() {
		return m_txtIPAddress.getText().toString();
	}

	public void pause() {
	}

	public void resume() {
	}

	public void refresh() {
	}

	// Custom Adapter for the Listview to display seen servers
	private class _MyServersAdapter extends ArrayAdapter<ServerInfo> {
		private final Context context;
		private final ServerInfo[] m_arrServers;

		public _MyServersAdapter(Context context, ServerInfo[] p_arrServers) {
			super(context, R.layout.cell_layout_displays, p_arrServers);
			this.context = context;
			this.m_arrServers = p_arrServers;
		}

		@Override
		public View getView(int p_iPosition, View convertView, ViewGroup parent) {
			LinearLayout lnrCell;
			TextView txtServerName, txtServerIP, txtLastSeen;
			ServerInfo oServer = m_arrServers[p_iPosition];

			// Reuse old view or create a new one?
			if (convertView != null) {
				lnrCell = (LinearLayout) convertView;
				LinearLayout lnrSubCell = (LinearLayout) lnrCell.getChildAt(1);
				txtServerName = (TextView) lnrCell.getChildAt(0);
				txtServerIP = (TextView) lnrSubCell.getChildAt(0);
				txtLastSeen = (TextView) lnrSubCell.getChildAt(1);

			} else {
				LayoutInflater inflater = (LayoutInflater) context
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				View cellView = inflater.inflate(R.layout.cell_server_info,
						null, false);
				lnrCell = (LinearLayout) cellView
						.findViewById(R.id.lnrServerInfoCell);
				txtServerName = (TextView) cellView
						.findViewById(R.id.txtServerName);
				txtServerIP = (TextView) cellView
						.findViewById(R.id.txtServerIP);
				txtLastSeen = (TextView) cellView
						.findViewById(R.id.txtLastSeen);

				txtServerName.setShadowLayer(3.0f, 2.0f, 2.0f, Color.LTGRAY);
			}
			// Build the cell
			Log.v(TAG, "(II) Server: " + oServer.toString());

			txtServerName.setText(oServer.getName());
			txtServerIP.setText(oServer.getIP());
			txtLastSeen.setText(oServer.getLastSeen().toLocaleString());
			lnrCell.setTag(oServer);
			return lnrCell;
		}

	}
}
